repeat loop
Course- R Programming >
A repeat
loop is used to iterate over a block of code multiple number of times. There is no condition check in repeat
loop to exit the loop. We must ourselves put a condition explicitly inside the body of the loop and use the break
statement to exit the loop. Failing to do so will result into an infinite loop.
Syntax of repeat
loop
repeat { statement }
In the statement
block, we must use the break
statement to exit the loop.
Flowchart of repeat
loop
Example of repeat
loop
x <- 1
repeat {
print(x)
x = x+1
if (x == 6){
break
}
}
Output
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5
In the above example, we have used a condition to check and exit the loop when x
takes the value of 6. Hence, we see in our output that only values from 1 to 5 get printed.